package com.example.administrator.myokhttpmvp.net;

import android.app.Application;
import android.content.Context;

import com.example.administrator.myokhttpmvp.utils.PrefManager;
import com.facebook.stetho.Stetho;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.https.HttpsUtils;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by zhy on 15/8/25.
 */
public class MyApplication extends Application {
    /**
     * 系统上下文
     */
    private static Context mAppContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mAppContext = getApplicationContext();
        PrefManager.initializeInstance(getApplicationContext(), "sssss");

//        Stetho.initializeWithDefaults(this);
        initOkHttp();//配置OkhttpClient
        Stetho.initializeWithDefaults(this);
    }

    /**
     * 获取系统上下文：用于ToastUtil类
     */
    public static Context getAppContext() {
        return mAppContext;
    }

    private void initOkHttp() {

//        ClearableCookieJar cookieJar1 = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getApplicationContext()));

        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);

//        CookieJarImpl cookieJar1 = new CookieJarImpl(new MemoryCookieStore());

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                .readTimeout(10000L, TimeUnit.MILLISECONDS)
                .addInterceptor(new LoggerInterceptor("TAG",true))
                .addNetworkInterceptor(new Interceptor() {//自定义拦截器
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request  = chain.request();
                        //配置统一的头
                        Request  newRequest     = request.newBuilder()
//                                .addHeader("","")
                                .addHeader("token", PrefManager.getInstance().get().getString(ServerApi.SP_TOKEN,"")).build();
                        return  chain.proceed(newRequest);
                    }
                })
//                .addNetworkInterceptor( new StethoInterceptor())//增加Stetho拦截器,用于调试
//                .cookieJar(cookieJar1)
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                .build();
        OkHttpUtils.initClient(okHttpClient);
    }
}
